package threadcreate01;

import java.util.stream.Stream;

public class thread06 {
    public static void main(String[] args) {
        sum s = new sum();
        int i = 50;
        producter p = new producter(s);
        consumer c = new consumer(s);
        new Thread(p, "生产者").start();
        new Thread(c, "消费者1").start();
        new Thread(c, "消费者2").start();
    }

    static class producter implements Runnable {
        public sum s;

        public producter(sum sum) {
            this.s = sum;
        }

        @Override
        public void run() {

            while (true) {
                s.add();
            }
        }
    }

    static class consumer implements Runnable {
        public sum s;

        public consumer(sum sum) {
            this.s = sum;
        }

        @Override
        public void run() {
            while (true) {
                s.reduce();
            }
        }
    }

    static class sum {
        private int sum;
        public static final int MAX = 30;
        public static final int MIN = 1;

        public synchronized void add() {
            if (sum < MAX) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "正在添加，然后现在有" + sum);
                sum++;
                notifyAll();
            } else {
                try {
                    wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        public synchronized void reduce() {
            if (sum >= MIN) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "正在减少，然后现在有" + sum);
                sum--;
                notifyAll();
            } else {
                try {
                    wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
